<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ajax上传文件</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
img {
	width: 168px;
	height: 126px;
	object-fit: cover;
	border: solid 1px #ccc;
	border-radius: 10px;
}


</style>
</head>
<body>
	<div class="formbody">
		<div class="formtitle">
			<span>ajax上传文件</span>
		</div>
		<form id="imageForm" enctype="multipart/form-data" method="post">
			<ul class="forminfo">
				<li><label>姓名</label>
				  <input name="name" type="text" value="西门吹雪" class="dfinput" />
				 </li>
				<li><label>学号</label>
				  <input name="num" type="text" value="12345" class="dfinput" />
				 </li>
				<li><label>上传照片</label>
				   <input name="photo" type="file" accept="image/*" class="dfinput" /> 
				   <input type="range" min="0" max="100"  value="0" id="range" />
				  </li>
				<li><img alt="照片" src="" id="photoPath"></li>
				<li><img alt="照片" src="" id="photoUlr"></li>
			</ul>
		</form>
	</div>
	<script language="JavaScript" src="js/jquery.js"></script>
	<script type="text/javascript">
		window.onload = function(){
			$("#photoPath").hide();
			$("#photoUlr").hide();
			$("input[type=file]").change(function(){
				var formData = new FormData(document.getElementById('imageForm'));
				var httpRequest = new XMLHttpRequest();
				//设置回调函数 来处理响应信息
				httpRequest.onreadystatechange = function(){
					if(httpRequest.readyState == 4 && httpRequest.status == 200){
						console.log(httpRequest.responseText);
						var $result = $.parseJSON(httpRequest.responseText);
						console.log($result);
						if($result.code == 200){
							$("#photoPath").attr("src","ShowImageServlet?imgPath="+$result.object.photo);
							$("#photoPath").show();
							$("#photoUlr").attr("src",""+$result.object.photoUrl);
							$("#photoUlr").show();
							
						}else{
							alert($result.message);
						}
					}
				}
				
				//监听文件上传的进度
				httpRequest.upload.onprogress = function(ev){
					console.log("上传进度:"+ev.loaded * 100/ev.total + "%");
					$("#range").val(ev.loaded * 100/ev.total);
				}
				
				//打开链接
				httpRequest.open("post","<%=basePath%>fileUploadAjaxServlet",true);
				httpRequest.send(formData);
				
			});
		}
	</script>
</body>
</html>
